package com.zhengxyou.jetpackdemo.lifecycle_liveData_viewModel.view_model;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.zhengxyou.jetpackdemo.R;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProviders;

/**
 * ViewModel数据共享
 */
public class BlankFragment extends Fragment {

    private CommunicateViewModel mViewModel;

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.blank_fragment, container, false);
    }

    private TextView tv_1;

    private int i = 0;

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        tv_1 = view.findViewById(R.id.tv_1);
        tv_1.setOnClickListener(v -> mViewModel.setName("BlankFragment is click " + ++i));
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        mViewModel = ViewModelProviders.of(getActivity()).get(CommunicateViewModel.class);
        mViewModel.getName().observe(this, s -> tv_1.setText(s));
    }

}
